//
//  WSSubscribeController.m
//  CharonTVProject
//
//  Created by karong on 2023/8/10.
//

#import "WSSubscribeController.h"
#import "WSSubscribeCell.h"
#import "WSPurchaseRequest.h"
#import "AppDelegate.h"
#import "WSPurchaseManager.h"
#import "WSGoods.h"
#import "CTMediator+WSUserCenterAction.h"

@interface WSSubscribeController ()<WSPurchaseManagerDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *listView;
@property (nonatomic, strong) NSArray * dataArray;
@property (weak, nonatomic) IBOutlet UIImageView *userImageView;
@property (weak, nonatomic) IBOutlet UILabel *coinsLabel;
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet YYLabel *label;
@property (nonatomic, assign) NSInteger selectIndex;
@end

@implementation WSSubscribeController
@synthesize dataArray = _dataArray;
- (void)viewDidLoad {
    [super viewDidLoad];
    self.label.attributedText = [self purchaseTitle];
    [self addObserver];
    [self layoutMainView];
    [self loadGoodsListRequest];
}

- (void)addObserver {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(layoutMainView) name:WSVipChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(layoutMainView) name:WSRefreshUserInfoNotification object:nil];
}

- (void)layoutMainView {
    self.userNameLabel.text = appUserCenter.user_name;
    self.coinsLabel.text = (appUserCenter.vip_status == 1)?WSSF(@"%@：%@",APPLocalized(@"會員有效期至"),appUserCenter.vip_expires_text):APPLocalized(@"開通VIP，隨時隨地免費看");
    [self.userImageView sd_setImageWithURL:[NSURL URLWithString:appUserCenter.avatar] placeholderImage:WSPlaceholderImage];
}

- (NSMutableAttributedString *)purchaseTitle {
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.alignment = NSTextAlignmentLeft;
    style.lineBreakMode = NSLineBreakByWordWrapping;
    NSString *text = APPLocalized(@"1、开通会员的用户可以观看有VIP标签的剧集，在该剧集下不再额外扣除剧豆 。账户余额剧豆 将在会员到期后继续使用\n2、单独的剧豆可用于在本产品内解锁付费剧集。未满18岁的用户不支持购买，剧豆为虚拟商品不支持无理由退款\n3、购买前请阅读《会员服务协议》（内含退订方式以及剧豆使用规则）\n4、如果碰到任何问题，请在我的页面联系我们或者给我们留言，我们会尽快与您联系");
    NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithString:text
                                                                                 attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12], NSParagraphStyleAttributeName: style, NSForegroundColorAttributeName: UIColor.font_white_ffffff}];
    NSString *string1 = APPLocalized(@"《會員服務協議》");
    NSRange range1 = [text rangeOfString:string1];
    [attrText addAttributes:@{NSUnderlineStyleAttributeName: @(1)} range:range1];
    [attrText setTextHighlightRange:range1 color:UIColor.font_yellow_FCB625 backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        UIViewController * target = [[CTMediator sharedInstance]ct_showWebWithUrl:API_CHARONTV_AGREEMENT_VIP titleStr:@"會員服務協議" showNav:YES closeHandle:^{}];
        [self.navigationController pushViewController:target animated:YES];
    }];
    
//    NSString *string2 = @"《自動續費付費規則》";
//    NSRange range2 = [text rangeOfString:string2];
//    [attrText addAttributes:@{NSUnderlineStyleAttributeName: @(1)} range:range2];
//    [attrText setTextHighlightRange:range2 color:UIColor.font_yellow_FCB625 backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
//        UIViewController * target = [[CTMediator sharedInstance]ct_showWebWithUrl:API_AGREEMENT_VIP_RENWAL titleStr:@"自動續費付費規則" showNav:YES closeHandle:^{}];
//        [self.navigationController pushViewController:target animated:YES];
//    }];
    return attrText;
}

- (void)loadGoodsListRequest {
    WeakSelf
    [WSToast loading];
    [WSPurchaseRequest loadcharonTV_GoodsListWithGoods_type:2 success:^(NSArray *array) {
        weakSelf.dataArray = array;
        [WSPurchaseManager shared].delegate = weakSelf;
        [WSPurchaseManager shared].products = array;
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (void)payGoods:(WSGoods *)goods {
    if (goods.SKProduct) {
        if (appUserCenter.isLogin) {
            [WSPurchaseManager shared].delegate = self;
            [[WSPurchaseManager shared] createOrderWithProduct:goods];
        }
        else {
            [((AppDelegate*)([UIApplication sharedApplication].delegate)) initMainPage];
        }
    }
}

- (IBAction)recordAction:(id)sender {
    UIViewController * target = [[CTMediator sharedInstance]ct_showcharonTV_CoinRecords];
    [self.navigationController pushViewController:target animated:YES];
}

- (IBAction)payAction:(id)sender {
    [self payGoods:self.dataArray[self.selectIndex]];
}


#pragma mark - WSPurchaseManagerDelegate
- (void)didAppleReceiveResponse {
    [WSToast dismiss];
    [self.listView reloadData];
}

- (void)purchaseManager:(WSPurchaseManager *)manager updateStatus:(WSPurchaseStatus)status object:(id)object {
    switch (status) {
        case WSPurchaseStatusSuccess:
        {
            
        }
            break;
        case WSPurchaseStatusCancel:
            [WSToast simple:APPLocalized(@"支付失敗")];
            break;
        default:
            break;
    }
}
#pragma mark UICollectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    WSSubscribeCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"WSSubscribeCell" forIndexPath:indexPath];
    [cell setDataWithObject:self.dataArray[indexPath.row] select:self.selectIndex == indexPath.row];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = CGSizeZero;
    size.width = 98;
    size.height = 98;
    return size;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
//    [self payGoods:self.dataArray[indexPath.row]];
    self.selectIndex = indexPath.row;
    [self.listView reloadData];
}

@end
